package net.litxuf.Util;



import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.io.File;

import org.apache.log4j.Logger;
import org.apache.commons.fileupload.FileItem;


/**
 * Created by IntelliJ IDEA.
 * User: HuMingBin
 * Date: 2006-9-10
 * Time: 17:19:21
 * To change this template use File | Settings | File Templates.
 */
public class WebUtil
{
    static Logger logger=Logger.getLogger(WebUtil.class);
    
    public static String filterAsJavascript(String text)
    {
        return text;
    }

        /**
     * parse int , if exception use defaultValue
     *
     * @param para
     * @param defaultValue
     * @return int
     */
    public static int parseIntPara(String para, int defaultValue) {
        if (para == null || para.trim().length() == 0) {
            return defaultValue;
        } else {
            try {
                return Integer.parseInt(para.trim());
            } catch (Exception e) {
                //e.printStackTrace();
                return defaultValue;
            }
        }
    }

    /**
     * parse float , if exception use defaultValue
     *
     * @param para
     * @param defaultValue
     * @return      float
     */
    public static float parseFloatPara(String para, float defaultValue) {
        if (para == null || para.trim().length() == 0) {
            return defaultValue;
        } else {
            try {
                return Float.parseFloat(para.trim());
            } catch (Exception e) {
                return defaultValue;
            }
        }
    }

    /**
     * parse long , if exception use defaultValue
     *
     * @param para
     * @param defaultValue
     * @return long
     */
    public static long parseLongPara(String para, long defaultValue) {
        if (para == null || para.trim().length() == 0) {
            return defaultValue;
        } else {
            try {
                return Long.parseLong(para.trim());
            } catch (Exception e) {
                return defaultValue;
            }
        }
    }


    public static String filterInHTMLDeleteBR(String value) {
        return filterInHTML(value).replaceAll("<br>", " ");
    }


    public static String filterInHTMLChangeBRToHard(String value) {
        return filterInHTML(value).replaceAll("<br>", "\r\n");
    }

    public static String filterInXML(String value) {
        if (value == null) {
            return ("");
        }
        char content[] = new char[value.length()];
        value.getChars(0, value.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
                case '<':
                    result.append("&lt;");
                    break;
                case '>':
                    result.append("&gt;");
                    break;
                case '&':
                    result.append("&amp;");
                    break;
                case '"':
                    result.append("&quot;");
                    break;
                case '\'':
                    result.append("&apos;");
                    break;
                default:
                    result.append(content[i]);
            }
        }
        return (result.toString());
    }

    public static String filterInTextArea(String value) {
        if (value == null) {
            return ("");
        }
        char content[] = new char[value.length()];
        value.getChars(0, value.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
                case '<':
                    result.append("&lt;");
                    break;
                case '>':
                    result.append("&gt;");
                    break;
                case '&':
                    result.append("&amp;");
                    break;
                case '"':
                    result.append("&quot;");
                    break;
                case '\'':
                    result.append("&#39;");
                    break;
                case ';':
                    result.append("&#59;");
                    break;
                default:
                    result.append(content[i]);
            }
        }
        return (result.toString());
    }

    public static String filterInScript(String value,int len)
    {
        return filterInScript(shortenStr(value,len));
    }

    public static String filterInScript(String value) {
        if (value == null) {
            return ("");
        }
        char content[] = new char[value.length()];
        value.getChars(0, value.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
                case '\\':
                    result.append("\\\\");
                    break;
                case '\'':
                    result.append("\\'");
                    break;
                case '\"':
                    result.append("\\\"");
                    break;
                case '\n':
                    result.append("\\n");
                    break;
                case '\r':
                    result.append("\\r");
                    break;
                //case '/':
                //    result.append("\\/");
                //    break;
                default:
                    result.append(content[i]);
            }
        }
        return (result.toString());
    }


    public static String cutForShow(String value, int lengthShown) {
   
        int point_num = 1;
        if (value == null) return "";
        if (lengthShown <= 0 || value.length() <= lengthShown) return value;
        return value.substring(0, lengthShown - point_num) + "...";
    }


    public static String filterInHTML(String value, int lengthShown) {
        if(value!=null) value=value.trim();
        int len=value.length();
        if(lengthShown>=len) {
            return filterInHTML(value);
        }
        else{
            return filterInHTML(value.substring(0,lengthShown))+ "...";
        }
    }

    public static String shortenStr(String value, int lengthShown){
        if(value==null) return "";
        value=value.trim();
        int len=value.length();
       // System.out.println("\n -------------==========000000000000====="+len);
        if(lengthShown>=len)
        {
            return value;
        }
        else
        {
            return value.substring(0,lengthShown);
        }
    }

    public static String shorten(String value, int lengthShown)
    {
       
    	if(value==null)return " ";
    	if(value!=null) value=value.trim();
        int len=value.length();
        if(lengthShown>=len)
        {
            return value;
        }
        else
        {
            return value.substring(0,lengthShown)+ "...";
        }
    }


    public static String filterInHTML(String value) {
        if (value == null) {
            return ("");
        }
        else value=value.trim();
        
        value = filterInTextArea(value);
        char content[] = new char[value.length()];
        value.getChars(0, value.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
                case ' ':
                    result.append(" ");
                    while (i + 1 < content.length && content[i + 1] == ' ') {
                        i++;
                        result.append("&nbsp;");
                    }
                    break;
                case '\n':
                case '\r':
                    if (i + 1 < content.length &&
                            (content[i + 1] == '\r' || content[i + 1] == '\n')) {
                        i++;
                    }
                    result.append("<br>");
                    break;
                default:
                    result.append(content[i]);
            }
        }
        return (result.toString());
    }

    public static String absoluteWidth(String txt) {
        return "<table style=\"table-layout:fixed;\" border=\"0\" width=\"100%\"><tr><td width=\"100%\" style=\"word-break:break-all\">"
                + txt + "</td></tr></table>";
    }

    public static String getRequestParameterOrAttribute(HttpServletRequest request, String parameterName) {
        if (parameterName == null) return "";
        String tmp = request.getParameter(parameterName);
        if (tmp == null || tmp.equals("")) {
            tmp = (String) request.getAttribute(parameterName);
        }
        if (tmp == null) {
            tmp = "";
        } else {
            tmp = tmp.trim();
        }
        return tmp;
    }

    public static String filterInHTMLKeepSpace(String value) {
        if (value == null) {
            return ("");
        }
      
        value = filterInTextArea(value);

        char content[] = new char[value.length()];
        value.getChars(0, value.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i])
            {
                case '\n':
                case '\r':
                    if (i + 1 < content.length &&
                            (content[i + 1] == '\r' || content[i + 1] == '\n')) {
                        i++;
                    }
                    result.append("<br>");
                    break;
                default:
                    result.append(content[i]);
            }
        }
        return (result.toString());
    }

    public static void listParatemers(HttpServletRequest request, Logger logger) {
        Enumeration e = request.getParameterNames();
        StringBuffer sb = new StringBuffer("\n-----------------------------------------------------\nlist parameters");
        for (; e.hasMoreElements();) {
            String para_name = (String) e.nextElement();
            sb.append("\n" + para_name + " = " + request.getParameter(para_name));
        }
        if (logger != null) {
            logger.debug(sb);
        }
    }

    public static int getIntParam(HttpServletRequest request, String name, int defaultValue) {
        return parseIntPara(request.getParameter(name), defaultValue);
    }

    public static long getLongParam(HttpServletRequest request, String name, long defaultValue) {
        return parseLongPara(request.getParameter(name), defaultValue);
    }

    public static float getFloatParam(HttpServletRequest request, String name, float defaultValue) {
        return parseFloatPara(request.getParameter(name), defaultValue);
    }

    public static int getIntAttri(HttpServletRequest request, String name, int defaultVale) {
        return parseIntPara((String) request.getAttribute(name), defaultVale);
    }

    public static long getLongAttri(HttpServletRequest request, String name, long defaultValue) {
        return parseLongPara((String) request.getAttribute(name), defaultValue);
    }

    public static float getFloatAttri(HttpServletRequest request, String name, float defaultValue) {
        return parseFloatPara((String) request.getAttribute(name), defaultValue);
    }

    /**
     * process file upload,
     *
     * @param fileItem
     * @param path     store path
     * @param name     store name
     * @return file url path
     */
    public static String uploadFile(FileItem fileItem, String path, String name) {
        if (fileItem != null && fileItem.getSize() > 0) {
            String picType = fileItem.getName();
            picType = picType.substring(picType.indexOf('.'));
            if (name == null) name = getRandomString(100000)+picType;
            else name = getRandomString(10000)+"_"+name+picType;
            logger.debug(fileItem.getName());
            String url = path + File.separator + name;
            logger.debug("url is " + url);
            File file = new File(path);
            if (!file.exists()) {
                logger.debug("create file");
                if (!file.mkdirs()) return null;
            }
            logger.debug("22222222");
            file = new File(url);
            if (file.exists()) file.delete();
            try {
                fileItem.write(new File(url));
            } catch (Exception e) {
                logger.debug("write file error" + e);
                return null;
            }
            return url;
        } else {
            return null;
        }
    }

    public static String uploadFile(FileItem fileItem, String path) {
        return uploadFile(fileItem, path, null);
    }

    public static String getFilterRequestString(HttpServletRequest request, String name) {
        return filterInHTML(request.getParameter(name));
    }

    public static String getRandomString(int max) {
        Random random = new Random(System.currentTimeMillis());
        return String.valueOf(random.nextInt(max));
    }

    public static byte getByteParameter(HttpServletRequest request, String name, byte defaultValue) {
        return parseBytePara(request.getParameter(name), defaultValue);
    }
    public static String getStringAttribute(HttpServletRequest request, String name)
    {
        return getStringAttribute(request, name,false);
    }
    public static String getStringAttribute(HttpServletRequest request, String name,boolean notrim)
    {
        String value=(String) request.getAttribute(name);
        return value==null?"":notrim?value:value.trim();
    }

    public static String getStringParameter(HttpServletRequest request, String name)
    {
        return getStringParameter(request, name,true);
    }
    public static String getStringParameter(HttpServletRequest request, String name,boolean notrim)
    {
        String value=request.getParameter(name);
        return value==null?"":notrim?value:value.trim();
    }

    private static byte parseBytePara(String para, byte defaultValue)
    {
        if (para == null || para.trim().length() == 0) {
            return defaultValue;
        } else {
            try {
                return Byte.parseByte(para.trim());
            } catch (Exception e) {
                return defaultValue;
            }
        }
    }
  
    	public static String Keyword(String uploadString, String dbString,String useReplaceFlag) {
    		String[] arrayname = dbString.split(",");
    		String newUploadString = "";
    		for (int i = 0; i < arrayname.length; i++) {
    			if ((uploadString.indexOf(arrayname[i]))>0) {
                    newUploadString = uploadString.replace(arrayname[i],useReplaceFlag);
    			}
    			uploadString=newUploadString;
    		}
    		return uploadString;
    	}
    	
    	public static String filterKeyword(String msg,List<String> list,String useReplaceFlag) {
    		
    		if(list!=null&&list.size()>0){
    			for(int i=0;i<list.size();i++){    				
    				String key=(String)list.get(i);
    				if(msg.indexOf(key)!=-1)msg=msg.replace(key, useReplaceFlag);
    				System.out.println(msg);
    			}
    		} 
    		return msg;
    	}
    	/**
    	 * "1,3,4"等数据 装化为hashset
    	 * Made in 2007-11-5上午10:09:27
    	 *  
    	 *@param val
    	 *@return
    	 *
    	 */
    	public static HashSet ToHashSet(String val){
    		if(val==null) return null;
    		HashSet<String>	hashSet = new HashSet<String>();
			String s[] = val.split(",");
			for (int i = 0; i < s.length; i++) {
				if (s[i].trim().length() == 0)
					continue;
				 
				hashSet.add(s[i].trim());
			}
			return hashSet;
    		
    	}
public static void main(String[] args) {
}
}
